from datetime import datetime
from io import BytesIO
import os
import re
import time
import uuid
from django.test import TestCase
import fitz
from flask import json
import openpyxl
import pandas as pd
from openpyxl import load_workbook
import requests
from doc_service.models import Report
from .yida_config import YidaClient
from oss_service.views import bucket,ds_bucket
import redis
import logging
from django.core.cache import cache
logger = logging.getLogger(__name__)
logging.basicConfig(
    filename='output.log',
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
client = redis.StrictRedis(
    host='10.8.0.83',
    port=6379,
    db=3,
    password=None,
    decode_responses=True
)
admin_user_id = "034728252633647035"
report_form_uuid = "FORM-5E859C69D49F452694E420EF7A162B4371MF"
finicial_form_uuid = "FORM-BAFAA96000BA4C44A0C8F3256EB00407RP4T"
person_form_uuid = "FORM-861F9E6F4AAE4D73A255247BF7991765XAKG"
yida_client = YidaClient()

class YidaTest(TestCase):
    def setUp(self) -> None:
        return super().setUp()
    
    def test_update_filed(self):
        '''修改字段'''
        for index,report_code in enumerate([
"CX01-0224425",
        ]):
            print(f"正在修改第{index+1}条：{report_code}")
            sn_code = 9993
            result = yida_client.update_form_data_by_field(report_form_uuid,
                                                    admin_user_id,
                                                    search_field=[
                                                        {
                                                            "type": "TEXT",
                                                            "operator": "eq",
                                                            "componentName": "TextField",
                                                            "key": "textField_lp93kxup",
                                                            "value": report_code
                                                        }
                                                    ],
                                                    update_field={
                                                        "textField_lp93kxup":"CX01-052442500014", # 报告编号
                                                        # "selectField_m5fq21fd":"钢结构", # 子类型
                                                        # "dateField_lphnrozp":1747094400000, # 委托日期
                                                        # "dateField_lp93kxx6": 1743638400000, #检测日期
                                                        # "dateField_lpgnxeft":1744934400000, #检测日期至
                                                        # "dateField_lpb39cyx": 1744934400000,# 签发日期
                                                        # "employeeField_lpkl919z":["4302516026430609"], # 审核人
                                                        # "textField_lpb65tvd":"挤塑板",# 材料名称
                                                        # "textField_lqbsdaaj":"0GF66M71HFZW5EM5DDC30B5QQY4T2VXDI7VCMIE9", # 模版编号
                                                        # "textField_lvg2c3u6":f"F24{str(sn_code+index).zfill(5)}", # 归档编号
                                                        # "textField_lvg2c3u6":f"CX01-012500002", # 归档编号
                                                        # "textField_lpb5xuuu":"NB-NH-KK-2025-16128", # 监管编号
                                                        # "selectField_lpgut0ng":"",# 检测1
                                                        # "selectField_lqeidrd3":"施桐垚-132058133925879495", #检测2
                                                        # "multiSelectField_lqwcqyd1":["201425144736285295","101430034232123441"], #组长组员id
                                                        # "employeeField_lqwgfnad":["201425144736285295","101430034232123441"], # 组长组员成员
                                                        # "textField_ltmlzgdv":"", # 签署信息
                                                        # "selectField_lpb4vtbt":"鉴定报告", #报告名称
                                                        # "selectField_lpgut0ng":"金振涛-304021431136688349", # 检测1
                                                        # "textField_ltgomz9t":"金振涛",# 检测1name
                                                        # "textField_lphpacz4":"桐庐县百江镇人民政府", #委托方
                                                        # "textField_lp93kxwq":"2000", #总检测费
                                                        # "textField_lqetx3jq":"潘百琴",
                                                        # "selectField_lpb4vtbt":"排查报告", #报告名称
                                                        # "selectField_lqwcqyd0":"04396438451212628", #编制员
                                                        # "employeeField_m1k1eva6":["04396438451212628"], #编制员成员
                                                        # "selectField_lp93kxv5":"可靠性鉴定", #工程类别
                                                        # "textField_lphpacz0":"安吉县溪龙乡溪源茶谷建设项目（1#楼-21#楼及地下室）", #工程名称
                                                        # "textField_lphrnneu":"杭州市余杭区仓前街道", #工程地址
                                                        # "selectField_m8ontrw2":"杭州防伪码", # 报告附加
                                                        # "selectField_m8ontrw2":"杭州防伪码（已上传）", # 报告附加
                                                        # "attachmentField_lqrz4ehj":[
                                                        #                                 {
                                                        #                                 "downloadUrl": f"https://api.zjcxjc.cn/api/v1/yida-app/common/download_file/out-pdf/202412/90bb0544-f7cb-46c5-8c4a-e156206f782f/attachmentField_lqrz4ehj/0-01623 浙江巨化热电有限公司节能增效技改项目.pdf",
                                                        #                                 "name": "01623 浙江巨化热电有限公司节能增效技改项目#12、#13机组 11.8.pdf",
                                                        #                                 "previewUrl": f"https://api.zjcxjc.cn/api/v1/yida-app/common/download_file/out-pdf/202412/90bb0544-f7cb-46c5-8c4a-e156206f782f/attachmentField_lqrz4ehj/0-01623 浙江巨化热电有限公司节能增效技改项目.pdf",
                                                        #                                 "url": f"https://api.zjcxjc.cn/api/v1/yida-app/common/download_file/out-pdf/202412/90bb0544-f7cb-46c5-8c4a-e156206f782f/attachmentField_lqrz4ehj/0-01623 浙江巨化热电有限公司节能增效技改项目.pdf",
                                                        #                                 "ext": "pdf"
                                                        #                                 }
                                                        #                             ]
                                                    })
        pass

    def test_update_filed_by_id(self):
        '''修改字段'''
        for index,form_inst_id in enumerate([
"dd730274-6ec9-457e-b426-0507a20e8d95",
        ]):
            print(f"正在修改第{index+1}条：{form_inst_id}")
            result = yida_client.update_form_data_by_id(report_form_uuid,
                                                    admin_user_id,
                                                    form_inst_id,
                                                    update_field={
                                                        "textField_lp93kxup":"CX01-050272500052", # 报告编号
                                                        # "selectField_m5c3p19j":"026", # 检测项目类别号
                                                        # "selectField_m5fq21fd":"材料", # 子类型
                                                        # "textField_lvg2c3u6":f"F24{str(sn_code+index).zfill(5)}", # 归档编号
                                                        # "textField_lvg2c3u6":f"CX01-012500002", # 归档编号
                                                        # "textField_lpb5xuuu":"NB-NH-KK-2025-16128", # 监管编号
                                                        # "selectField_lpgut0ng":"",# 检测1
                                                        # "selectField_lqeidrd3":"吕松-17386153151314238974", #检测2
                                                        # "multiSelectField_lqwcqyd1":["201425144736285295","101430034232123441"], #组长组员id
                                                        # "employeeField_lqwgfnad":["201425144736285295","101430034232123441"], # 组长组员成员
                                                        # "textField_ltmlzgdv":"", # 签署信息
                                                        # "selectField_lpb4vtbt":"鉴定报告", #报告名称
                                                        # "selectField_lpgut0ng":"金振涛-304021431136688349", # 检测1
                                                        # "textField_ltgomz9t":"金振涛",# 检测1name
                                                        # "textField_lphpacz4":"桐庐县百江镇人民政府", #委托方
                                                        # "textField_lp93kxwq":"2000", #总检测费
                                                        # "textField_lqetx3jq":"潘百琴",
                                                        # "selectField_lpb4vtbt":"排查报告", #报告名称
                                                        # "dateField_lpb39cyx": 1739404800000,# 签发日期
                                                        # "dateField_lp93kxx6": 1734307200000, #检测日期
                                                        # "dateField_lpgnxeft":0, #检测日期至
                                                        # "selectField_lqwcqyd0":"04396438451212628", #编制员
                                                        # "employeeField_m1k1eva6":["04396438451212628"], #编制员成员
                                                        # "dateField_lphnrozp":1714521600000, # 委托日期
                                                        # "selectField_lp93kxv5":"可靠性鉴定", #工程类别
                                                        "textField_lphpacz0":"安吉县溪龙乡溪源茶谷建设项目（1#楼-21#楼及地下室）", #工程名称
                                                    })


    def test_add_group_member(self):
        '''修改字段'''
        for index,report_code in enumerate([
"CX01-050512500007",
"CX01-050512500008",
"CX01-050512500009",
"CX01-050512500010",
        ]):
            print(f"正在修改第{index+1}条：{report_code}")
            user_id = ["636969001127484058"]
            result = yida_client.get_form_data_by_search_field(report_form_uuid,
                                                      admin_user_id,
                                                      search_field=[
                                                        {
                                                            "type": "TEXT",
                                                            "operator": "eq",
                                                            "componentName": "TextField",
                                                            "key": "textField_lp93kxup",
                                                            "value": report_code
                                                        }
                                                    ])
            member_group = result[0].form_data.get("employeeField_lqwgfnad_id")
            update_result = yida_client.update_form_data_by_id(report_form_uuid,
                                                    admin_user_id,
                                                    result[0].form_instance_id,
                                                    update_field={
                                                        "employeeField_lqwgfnad":member_group+user_id
                                                    })
            if update_result == "success":
                print(f"成功修改{result[0].form_instance_id}")
            else:
                print(f"修改失败{result[0].form_instance_id}")
        return

    def test_update_person_info(self):
        '''重置登记日期'''
        for index,ding_id in enumerate([
"010024563026267706",
"01003239585120217040",
"01005023422036340992",
"01024103261821416059",
"01040042436626194372",
"01055365476326417745",
"0108103964281059843",
"0108640969838382",
"01140541350021494563",
"01153642065129897820",
"0117324356611230682",
"01174764625621413597",
"01185546302638597980",
"01190717635924228071",
"01196843350239746353",
"012035271224228189",
"01241605492126058737",
"01241614681324279639",
"0124220247848284",
"01252358376524307673",
"01260926206727765191",
"01315620521839806924",
"01426234452923433",
"01435150413637976559",
"01523235383728774632",
"01525509238261",
"01530133420033080528",
"015342550458656134",
"01591134156631198933",
"016605464324256585",
"020168151849846095",
"0203500308664114",
"020949060737642799",
"02102832031070631",
"02144408938275",
"021713304535988715",
"022127532333720855",
"02216616155129174389",
"022456592407854850",
"02335200004721732668",
"02342435372836721860",
"02343330052636768142",
"02344009552324228071",
"02345855436225944765",
"02346708193726104572",
"023519152707886809",
"02360826035624352",
"02393949355629101273",
"024008502835938140",
"024021201326222852",
"02406509264226222852",
"024958223927323249",
"02505632668803",
"025246214427869486",
"0255646861738",
"02570117063238142913",
"030904610027626954",
"0317320733895033",
"03200553147637",
"03210101282137753288",
"032331201649699235",
"03284438516546",
"03381908401181880",
"034728252633647035",
"034852504233076425",
"0400446050954996",
"0401126665245",
"04011267121698",
"04011267414561",
"0401131318699235",
"04011328158332",
"040731181626440455",
"0413331562660",
"0424463207896262",
"042512020120867332",
"043050546726320277",
"04396438451212628",
"050657362421887111",
"05556956311218827",
"055913094021431798",
"0618113306697857",
"0634044254774477",
"065236266832784341",
"0658110137955104",
"066826673026353878",
"066832433821594435",
"073425255626114865",
"0761653840699093",
"0809654940659317",
"0834460332681700",
"0844313817899755",
"084660281429605060",
"085101005229279227",
"08685915611002753",
"090163193538201908",
"092141065829080863",
"092742303437749608",
"092936545221452136",
"093033564335126502",
"09342356591186722",
"094652116229318502",
"094919345226799436",
"096504501526386719",
"101430034232123441",
"103738270839828199",
"103750080736589540",
"105747306330082136",
"105868473623215122",
"105953316439049625",
"1144202265683131",
"114645206521512577",
"114846014624356482",
"1166642942893338",
"1203591811846049",
"121514153926452611",
"121637331121392576",
"122403331527439707",
"12245534121221711",
"12316948061043635",
"1232135462828471",
"124122525633425726",
"124254002120895921",
"124255173821423056",
"1244562412898775",
"125308475729094349",
"126103212521541047",
"130450183127906398",
"131844193726064731",
"13205619221223127",
"132058133925879495",
"132368606536835920",
"133202036533510868",
"133817262821377093",
"135500335322974728",
"135857214829549984",
"140037132726116631",
"1410641735697591",
"142039684424167375",
"1420432047940374",
"142331232038303347",
"1459033249784380",
"152137290927173198",
"155825676333585313",
"1615541323778639",
"166955616626216826",
"171040542526210932",
"171124350339790638",
"17386153151314238974",
"174400291321878900",
"176226386838151321",
"176626543236441164",
"1813186945679370",
"181653211935514922",
"181868115021403358",
"1853210647903618",
"185367084937640164",
"192964425024840839",
"193026212521178405",
"1967151646787412",
"200545431820038778",
"201425144736285295",
"201530554626214237",
"2019354045778380",
"211437455021410985",
"216633355439426104",
"224960025138150441",
"226463202923238514",
"2312544651844401",
"231415422935283754",
"2422306733845200",
"2563636311618364662",
"2569602548793559",
"261139254224191205",
"261149476629066614",
"26115902031186933",
"261310384126093212",
"262952004337952570",
"2633343336752258",
"264710343424020085",
"264914196539488689",
"2666195119921619",
"266701641426238823",
"273061403936535084",
"273464525536237122",
"274406420126379325",
"27536165031140846422",
"275606151921621235",
"2804202606682418",
"2806360310694323",
"281750473821183949",
"283018485436697534",
"283115273526639999",
"283146214137752096",
"2831573606669551099",
"283549251424046526",
"2847102833903162",
"293760243232505015",
"295346234326594474",
"296836250826290258",
"301546025724261514",
"303924331339769365",
"304021431136688349",
"304657190033504463",
"30491745091160234",
"306109654123518519",
"310962401432399126",
"312737305223557398",
"3209321238850004",
"326233461048779",
"3338163839791740",
"353229005056",
"355110096639775703",
"362722146421172630",
"3702383117938462",
"37393642101067598",
"383267142424342951",
"3918605429606283",
"4241481100656183",
"4302516026430609",
"4321054729252524",
"433219161421025528",
"433922205023728257",
"4343032539754359",
"434611412438159871",
"441969542438319094",
"454162580625813806",
"465059002238896773",
"470129525829268066",
"473955234326172840",
"481266243121408210",
"483447211326330255",
"483619346320641821",
"485008463123273331",
"4863506953774960",
"490802281225011333",
"492258201131618",
"494404481026103423",
"495353353824105095",
"4956644254835454",
"496917636926485746",
"501310113725972036",
"512763636427162545",
"5211483526684559",
"525533233724080549",
"542638066136921074",
"551348590326315483",
"5664225269943443",
"57134964181156408",
"602607252636704456",
"613911141126549565",
"630217105227441512",
"634528236736460091",
"636969001127484058",
"640405026720700825",
"645500156128886275",
"65126029311212887",
"684218056439892302",
"6952182711784861",
        ]):
            print(f"正在修改第{index+1}条：{ding_id}")
            result = yida_client.update_form_data_by_field(person_form_uuid,
                                                    admin_user_id,
                                                    search_field=[
                                                        {
                                                            "type": "TEXT",
                                                            "operator": "eq",
                                                            "componentName": "TextField",
                                                            "key": "textField_lp0zbal4",
                                                            "value": ding_id
                                                        }
                                                    ],
                                                    update_field={
                                                        "numberField_mbfsp25c":90, # 登记日期限制
                                                    })
            
    def sync_finicial_data(self):
        file_path = "/Users/xusijiao/Downloads/项目信息-流程_2025_20250310174620.xlsx"
        wb = openpyxl.load_workbook(file_path)
        ws = wb.active
        reports = []
        for row in ws.iter_rows(min_row=2, max_col=5, values_only=True):
            reports.append(row)
        for index,report in enumerate(reports):
            print(f"正在处理第{index}条：{report[0]}")
            report_code = report[0]
            total_amount = report[1]
            report_id = report[2]
            bzy_id = report[3]
            sign_date = report[4]
            result = yida_client.get_form_data_by_search_field(finicial_form_uuid,
                                                      admin_user_id,
                                                      [
                                                        {
                                                            "type": "TEXT",
                                                            "operator": "eq",
                                                            "componentName": "TextField",
                                                            "key": "textField_ltmbnezf",
                                                            "value": report_code
                                                        }
                                                      ])
            if not result:
                date = datetime.strptime(sign_date, "%Y-%m-%d")
                datestamp = int(date.timestamp())*1000
                res = yida_client.create_process_instance(finicial_form_uuid,
                                             admin_user_id,
                                             {
                                              "textField_ltmbnezf":report_code,
                                              "numberField_lv0lyit8": float(total_amount), #总检测金额
                                              "textField_m40urbcv": report_id, #报告实例id
                                              "textField_m4j9xdl0": bzy_id, #编制员id
                                              "dateField_lv0uftfc": datestamp, #登记日期
                                             },
                                             "TPROC--HT866U91DJ5KWCDDFPUDJ892JZEX24PYH42VL5"
                                            )
                print(res)
    def test_update_data(self):
        # 加载output.json文件
        with open("/Users/xusijiao/Desktop/xiaming_py/reportservice/yida_app_service/chengxiang/resorce/output.json", "r") as f:
            data:list = json.load(f)
            data_arr = [
                ("CXHJ-QJ-2400022"	,"7fef2757-602f-4ff3-9d84-3313786ef5c5"),
                ("CXCF-WC-2400039"	,"5b633dcd-0794-42ab-bcee-1447ff8b5851"),
                ("CXHL-KC-2400144"	,"733c2acc-22e1-43d2-b5e8-18763eb9dc5b"),
            ]
            # test_update_data
            index = 1
            for report_code,order_no in data_arr:
                report = next((order for order in data if order["orderNo"] == order_no), None)
                if report:
                    print(f"正在修改第{index}条:{report_code}")
                    index += 1
                    update_result = yida_client.update_form_data_by_field(report_form_uuid,
                                                          admin_user_id,
                                                          [
                                                              {
                                                                "type": "TEXT",
                                                                "operator": "eq",
                                                                "componentName": "TextField",
                                                                "key": "textField_lp93kxup",
                                                                "value": report_code
                                                              }
                                                          ],
                                                          {
                                                              "textField_ltmlzgdv": json.dumps(report)
                                                          }
                                                          )
                    print(update_result)


    def test_script(self):
        '''修改报告编号'''
        result = yida_client.update_form_data_by_id(report_form_uuid,
                                                    admin_user_id,
                                                    form_inst_id="2790d010-a240-4d0e-9d1a-29adf98282d6",
                                                    update_field={
                                                        "textField_lp93kxup":"CXFL-HY-2400269" #报告编号
                                                    })
    
    def test_add_print_task(self):
        redis_client = redis.StrictRedis(host='10.8.0.83', port=6379, db=6,decode_responses=True)
        form_inst_ids = [
"c34b035f-6e0d-4874-940e-faf3411b5811",
"20338bd6-72c1-4652-b324-4a64f9c9d576",
"059863c0-4d04-4966-a63d-0d784e68176a",
"dbdc48a0-bfa6-4909-97e2-7d83d68efbe4",
"3c1b900a-6c65-4913-8c1e-056e259aaefe",
"4290d16e-a222-42a8-a56d-0e7c5556c095",
"ff5ea215-fd24-4390-b78c-831ad0f0db1f",
"a8d16a64-55de-4f71-ad29-fad1c33f9513",
"62f97f05-d3b6-4770-ae2a-efd17514d10f",
"1d51ade7-659d-45e1-a68b-f3c097760b8b",
"270cbd65-743d-4277-9bc5-84573d22dadd",
"a0293655-832a-4485-8529-6e8329242eb6",
"ff1fd51c-601b-4474-8c30-bc95cbca2540",
"9abefba4-2699-4a65-b474-e5f95ba68840",
"833aaa0b-010f-41aa-8407-20f066a3921c",
"de5eb3ec-deee-4b34-b938-3279e123d8d3",
"5cf133ae-5784-4bb5-aace-c2ea4d2e8b65",
"636006bd-3f73-42e7-98e1-855fc86df1ba",
"d1f6027e-9578-4d71-97db-d61cf49da2a8",
"8f6d9fbf-d7e0-4060-bbf4-2f4ee763bcb6",
"4aadc454-4d18-4a28-9c5e-fc7e89982de4",
        ]
        for form_inst_id in form_inst_ids:
            redis_client.lpush("print_task",form_inst_id)

    def test_archive_id_script(self):
        '''修改归档编号'''
        prefix = "F24"
        code = 1833
        for report in [
            "CXCF-RA-2400017"
        ]:
            print(f"正在修改{report}")
            result = yida_client.update_form_data_by_field(report_form_uuid,
                                                  admin_user_id,
                                                  [
                                                      {
                                                        "type": "TEXT",
                                                        "operator": "eq",
                                                        "componentName": "TextField",
                                                        "key": "textField_lp93kxup",
                                                        "value": report
                                                      }
                                                  ],
                                                  update_field={
                                                        "textField_lvg2c3u6":f"{prefix}{str(code).zfill(5)}",
                                                        "numberField_lvg2c3u5":code
                                                    }
                                                  )
            code += 1
            if result == "success":
                print("修改成功")
            # result = yida_client.update_form_data_by_id(report_form_uuid,
            #                                         admin_user_id,
            #                                         form_inst_id="3dda5dd1-362a-4781-954d-d08b104118f3",
            #                                         update_field={
            #                                             "textField_lvg2c3u6":"J2404452",
            #                                             "numberField_lvg2c3u5":4452 #报告编号
            #                                         })
    def test_group_info_script(self):
        '''修改组长组员'''
        bzy_ids = ["362722146421172630","293760243232505015","501310113725972036","296836250826290258","012035271224228189","273464525536237122"] #编制员id
        leader_id = "101430034232123441" # 组长id
        for bzy_id in bzy_ids:
            print(f"正在更新编制员：{bzy_id}")
            res_search,total = yida_client.get_all_form_data_by_search_field(report_form_uuid,
                                                          admin_user_id,
                                                          [{"key":"employeeField_lqwgfnad","value":bzy_id,"type":"STRING","operator":"eq","componentName":"EmployeeField"}])
            print(f"总计：{total}")
            for index,report in enumerate(res_search):
                print(f"正在修改第{index+1}条:{report.form_instance_id}")
                result = yida_client.update_form_data_by_id(report_form_uuid,
                                                        admin_user_id,
                                                        form_inst_id=report.form_instance_id,
                                                        update_field={
                                                              "multiSelectField_lqwcqyd1":[
                                                                    bzy_id,
                                                                    leader_id
                                                              ],
                                                              "employeeField_lqwgfnad": [
                                                                    bzy_id,
                                                                    leader_id
                                                              ]
                                                          })
                print(result)
                time.sleep(2)
    
    def test_update_model(self):
        '''修改模版编号'''
        for form_inst_id in [
            "a9d09538-3f94-45de-85df-605fd0f89f05",
            "cc2f41d0-2a50-48b7-bf24-85b8d808ea08",
            "251d6914-6217-41e5-9588-f52ae6d79333",
            "cc9bf6af-fa74-487e-99f8-5f466c0d44ac",
            "d6219900-467f-47a2-ad2f-d03c20dc7dd4",
            "0643fd4b-7995-41d9-961c-45fb8278a883",
        ]:
            result = yida_client.update_form_data_by_id(report_form_uuid,
                                                        admin_user_id,
                                                        form_inst_id=form_inst_id,
                                                        update_field={
                                                            "textField_lqbsdaaj":"VVC66HB12V0QT1LPFPTFZ8N6X8CO2ZIS8N23M2", #模版编号
                                                        })
            print(f">>>>>{result}")
    
    def test_update_zg(self):
        '''修改总工'''
        for form_inst_id in [
            "c9359ef8-9ec9-438a-96d8-cf78eeb2479b",
        ]:
            result = yida_client.update_form_data_by_id(report_form_uuid,
                                                    admin_user_id,
                                                    form_inst_id=form_inst_id,
                                                    update_field={
                                                        "employeeField_lqkmu48d":["1410641735697591"], #一级总工
                                                        "employeeField_lq4t9qtu":["1410641735697591"], # 三级总工
                                                    })
            print("form_inst_id>>>>",form_inst_id)
    def test_script_1(self):
        '''
        修改材料审核人和三级总工
        李素娇：4302516026430609
        黄国亮：303924331339769365
        '''
        for form_inst_id in [
            "75fc7f3b-cd60-4f83-b1a7-89d85e66f337",
            "f4521df8-9d93-4f78-a00e-5ff9ac7c711a",
        ]:
            result = yida_client.update_form_data_by_id(report_form_uuid,
                                                    admin_user_id,
                                                    form_inst_id=form_inst_id,
                                                    update_field={
                                                        "employeeField_lpkl919z":["4302516026430609"], #审核人
                                                        "employeeField_lq4t9qtu":["303924331339769365"], # 三级总工
                                                        "textField_lqbsdaaj":"VBD66H817MCHPX1W9JKFX8KTOGTF2E90F3WQL4O3" # 模版编号
                                                    })
            print("form_inst_id>>>>",form_inst_id)
        pass
        
            
    def test_update_bzy(self):
        '''更新编制员'''
        form_uuid = report_form_uuid
        person_form_uuid = "FORM-861F9E6F4AAE4D73A255247BF7991765XAKG"
        form_inst_id = "9b49fad1-5311-4bc3-87a4-f1fd6bc4a18b"
        res = yida_client.get_form_items_by_ids(form_uuid,form_inst_id,admin_user_id)
        form_data = res[0].form_data
        name = form_data.get('textField_lrd6lxm1') # 编制人name
        bzy_select = form_data.get('selectField_lqwcqyd0') #编制员
        bzy_select_id = form_data.get('selectField_lqwcqyd0_id')
        if (not bzy_select_id) or (name == bzy_select):
            return
        person_res = yida_client.get_form_data_by_search_field(person_form_uuid,admin_user_id,[
            {
              "type": "TEXT",
              "operator": "eq",
              "componentName": "TextField",
              "key": "textField_lp0tv654",
              "value": name
            }
          ])
        person_instance = person_res[0].form_data
        person_id = person_instance.get("textField_lp0zbal4")
        if bzy_select_id == person_id:
            return
        else:
            result = yida_client.update_form_data_by_id(form_uuid,admin_user_id,form_inst_id,{
                "selectField_lqwcqyd0":person_id,
            })
        pass

    def test_batch_delete_record(self):
        '''批量删除记录'''
        form_inst_ids = [
            "d2189732-f30e-44ce-bc63-9cce3fba0b5d",
            "0baca832-9d96-4296-a679-ec3e96e1065c",
        ]
        for index,form_inst_id in enumerate(form_inst_ids):
            result = yida_client.delete_form_data(form_inst_id,admin_user_id)
            print(f"第{index}条删除结果>>>>",result)


    def test_recreate_finicial(self):
        '''重新生成财务'''
        report_codes = [
            "CXEM-WX-2400001",
        ]
        for index,report_code in enumerate(report_codes):
            print("正在处理第",index,"条数据")
            form_uuid = "FORM-BAFAA96000BA4C44A0C8F3256EB00407RP4T"
            user_id = "034728252633647035"
            result = yida_client.get_form_data_by_search_field(form_uuid,admin_user_id,[
                {
                  "type": "TEXT",
                  "operator": "eq",
                  "componentName": "TextField",
                  "key": "textField_ltmbnezf",
                  "value": report_code
                }
            ])
            if result and len(result) == 1:
                form_inst_id = result[0].form_instance_id
                del_result = yida_client.delete_form_data(form_inst_id,admin_user_id)
                print("删除结果>>>>",del_result)
            else:
                print("未找到对应数据")
            res = yida_client.get_form_data_by_search_field(report_form_uuid,
                                                      admin_user_id,[
                                                          {
                                                              "type": "TEXT",
                                                              "operator": "eq",
                                                              "componentName": "TextField",
                                                              "key": "textField_lp93kxup",
                                                              "value": report_code
                                                          }
                                                      ])
            res = res[0].form_data
            try:
                amount = int(res.get("textField_lp93kxwq"))
            except:
                amount = 0
            create_result = yida_client.create_process_instance(form_uuid,user_id,{
                "textField_ltmbnezf":report_code,
                "numberField_lv0lyit8":amount,
            },
            "TPROC--HT866U91DJ5KWCDDFPUDJ892JZEX24PYH42VL5")
            print(">>>>>>",create_result)

    def sync_finicial_ywy(self):
        '''同步财务业务员'''
        ywy_name = "刘兴忠"
        reports,total = yida_client.get_all_form_data_by_search_field(report_form_uuid,
                                                      admin_user_id,
                                                      [
                                                          {
                                                            "type": "TEXT",
                                                            "operator": "eq",
                                                            "componentName": "TextField",
                                                            "key": "textField_lqetx3jq",
                                                            "value": ywy_name
                                                          }
                                                      ])
        for index,report in enumerate(reports):
            report_code = report.form_data.get('textField_lp93kxup')
            print(f"正在处理第{index}条数据:{report_code}")
            finicial_data = yida_client.get_form_data_by_search_field(finicial_form_uuid,
                                                      admin_user_id,
                                                      [
                                                          {
                                                            "type": "TEXT",
                                                            "operator": "eq",
                                                            "componentName": "TextField",
                                                            "key": "textField_ltmbnezf",
                                                            "value": report_code
                                                          }
                                                      ])
            if finicial_data:
                ywy = finicial_data[0].form_data.get("textField_m8du9yoi")
                if ywy != ywy_name:
                    result = yida_client.update_form_data_by_id(finicial_form_uuid,admin_user_id,finicial_data[0].form_instance_id,{
                        "textField_m8du9yoi":ywy_name,
                    })
                    print("更新财务业务员结果>>>>",result)




    def test_update_group_info(self):
        '''更新成员组信息'''
        name = "缪明燕"
        form_uuid = "FORM-861F9E6F4AAE4D73A255247BF7991765XAKG" # 成员表
        report_form_uuid = report_form_uuid # 报告表
        person_result = yida_client.get_form_data_by_search_field(form_uuid,admin_user_id,[
            {
              "type": "TEXT",
              "operator": "eq",
              "componentName": "TextField",
              "key": "textField_lp0tv654",
              "value": name
            }
        ])
        form_data = person_result[0].form_data
        id = form_data.get("textField_lp0zbal4")
        group_members = form_data.get("multiSelectField_lqwb9ix2_id") + [name+"-"+id]
        for index,member in enumerate(group_members):
            # if member != name+"-"+id: # 编制员不是组长
            #     continue
            if "-" in member:
                member_name = member.split("-")[0]
                member_id = member.split("-")[1]
            else:
                print("未找到对应数据")
                continue
            member_reports,total = yida_client.get_all_form_data_by_search_field(report_form_uuid,admin_user_id,[
                {
                    "type": "TEXT",
                    "operator": "eq",
                    "componentName": "SelectField",
                    "key": "selectField_lqwcqyd0",
                    "value": member_id
                }
            ])
            print(f"共找到{member_name}报告，共计{total}条")
            for report in member_reports:
                form_inst_id = report.form_instance_id
                group_ids:list = report.form_data.get("multiSelectField_lqwcqyd1")
                if id not in group_ids:
                    group_member_ids = [
                                            item.split("-")[1] for item in group_members if "-" in item
                                        ]+[id]
                    update_result = yida_client.update_form_data_by_id(report_form_uuid,
                                                       admin_user_id,
                                                       form_inst_id,{
                                                           "multiSelectField_lqwcqyd1":group_member_ids,
                                                           "employeeField_lqwgfnad": group_member_ids
                                                       })
                    print(f"成功修改{form_inst_id}")

    def test_batch_approve_report(self):
        '''批量审批报告'''
        report_codes = [
            "CXAD-LP-2400004",
        ]
        # for code in range(1123,1413):
        #     report_code = "CXAC-YH-240"+str(code)
        for report_code in report_codes:
            result = yida_client.get_process_data_by_search_field(report_form_uuid,
                                                  admin_user_id,[
                                                      {
                                                        "type": "TEXT",
                                                        "operator": "eq",
                                                        "componentName": "TextField",
                                                        "key": "textField_lp93kxup",
                                                        "value": report_code
                                                      }
                                                  ])
            process_instance_id = result[0].process_instance_id
            history = yida_client.get_approve_history(process_instance_id,"4302516026430609")
            for item in history:
                if item.show_name in ["待审核"]:
                    yida_client.execute_task(process_instance_id,item.task_id,"4302516026430609")
                    time.sleep(3)
            pass
            # yida_client.execute_task()
    def test_batch_upload_pdf(self):
        '''批量替换更新报告'''
        path = "/Users/xusijiao/Downloads/sss"
        file_names = list_pdf_files(path)
        for index,file_name in enumerate(file_names):
            print("正在处理第",index,"条数据")
            file_path = os.path.join(path,file_name)
            report_code = file_name.split(".")[0]
            res = yida_client.get_form_data_by_search_field(report_form_uuid,
                                                      admin_user_id,[
                                                          {
                                                            "type": "TEXT",
                                                            "operator": "eq",
                                                            "componentName": "TextField",
                                                            "key": "textField_lp93kxup",
                                                            "value": report_code
                                                          }
                                                      ]
            )
            if res:
                form_inst_id = res[0].form_instance_id
                object_key = f"yida-app/chengxiang/report_origin/{file_name}"
                bucket.put_object_from_file(object_key,file_path)
                xm_url = f"https://api.zjcxjc.cn/api/v1/yida-app/common/download_file/{object_key}"
                result = yida_client.update_form_data_by_id(report_form_uuid,admin_user_id,form_inst_id,{
                    "attachmentField_lqrz4ehj":[
                          {
                          "downloadUrl": xm_url,
                          "name": file_name,
                          "previewUrl": xm_url,
                          "url": xm_url,
                          "ext": "pdf"
                          }
                      ]
                })
                print(">>>>>>",result)
            else:
                print("未找到对应数据")
                continue
    def test_correct_bzy(self):
        '''修正编制员和编制人name'''
        name = "陈东"
        user_id = "04396438451212628"
        yida_client = YidaClient()
        result = yida_client.get_form_data_by_search_field(report_form_uuid,
                                                  admin_user_id,
                                                  [
                                                      {
                                                        "type": "TEXT",
                                                        "operator": "ne",
                                                        "componentName": "TextField",
                                                        "key": "textField_lrd6lxm1",
                                                        "value": name
                                                      },
                                                      {
                                                        "type": "ARRAY",
                                                        "operator": "eq",
                                                        "componentName": "SelectField",
                                                        "key": "selectField_lqwcqyd0",
                                                        "value": user_id
                                                      },
                                                  ],
                                                  page_size=100,
                                                  start_time="2024-09-01")
        for report in result:
            bzy_name = report.form_data.get("textField_lrd6lxm1")
            print(bzy_name)
            if bzy_name != name:
                print("正在修正>>>",report.form_instance_id)
                person_res = yida_client.get_form_data_by_search_field("FORM-861F9E6F4AAE4D73A255247BF7991765XAKG",admin_user_id,[
                      {
                        "type": "TEXT",
                        "operator": "eq",
                        "componentName": "TextField",
                        "key": "textField_lp0tv654",
                        "value": bzy_name
                      }
                    ])
                person_instance = person_res[0].form_data
                person_id = person_instance.get("textField_lp0zbal4")
                update_res = yida_client.update_form_data_by_id(report_form_uuid,
                                                   admin_user_id,
                                                   report.form_instance_id,
                                                   {
                                                        "selectField_lqwcqyd0":person_id
                                                   })
                print(update_res)
        pass

    def test_digital_sign_add_record(self):
        '''电子签章插队'''
        records = [
"95434661-9626-494d-ad97-0e8356a2be49",
"92ee81e6-e794-49e7-b078-c7f9aeccd8b4",
"f5a33f47-7ff6-44f2-8075-d95e24c558b6",
"657c67bb-6117-4d1b-b39b-c5e4daea1bf3",
"6f193493-35fd-44cc-bc4f-1a8c38cec02e",
"3434cc5c-e23a-4bf7-aa69-e0975392f048",
"9b62aeba-576a-47f4-ba15-70685675d599",
"58e3a3f9-a82f-4258-9b24-faa3c35898ef",
"2199e164-4fd5-4ef8-9653-b40f633e16a2",
"c2719173-ed03-4719-93a5-3c94f4060569",
"d912a02b-06d7-44ed-bc18-465412e95c4c",
"465b01a6-f33c-4005-a8ce-2a368e41c8f3",
"29b77501-4714-414b-927e-967f06bfffd7",
"7f1309fb-5845-4e0c-a93f-ddb12ae29a89",
"1aec20f8-9d73-4225-9725-f13ba12d3b12",
"6e12094f-60fb-405a-8579-0e4104ab5bb8",
"6d737505-c2b5-42e0-8d10-4c5adf0640a1",
"463290f8-a2c3-47be-92e9-6f25dd76e4b4",
"1b4e420d-0f03-4fd9-8f5f-c135a1976391",
"1537ed2b-6899-47f5-ab1a-39861f4eac2c",
"8bf4751c-ad48-444a-a8a9-d4e3a4dc86e9",
"aaad0522-c5f5-4f26-900a-ad3ffb939dd8",
"5cb03029-76f0-4349-99f4-7aabf39aa812",
"00f7f788-52f9-444a-8f45-721325ce3357",
"d443443d-8bca-4606-9e9b-d20fa2526f6a",
"69e6f3e3-8442-4377-a1fb-835329578f2b",
"1df516ff-7240-45a1-a132-81efd5fa3313",
"038484bf-d5e2-43d6-8876-e4eee1cfe10e",
"3c463c58-e79d-4581-85ac-fab85a691e9e",
"e6990379-0129-4569-b292-823b14393506",
"cb8ed18b-a1bd-4245-b4fb-da75cc01c0e5",
"24c52ed4-3a8d-4f1a-b7ea-a67248748f8f",
"2cb60a9b-84ff-464f-a6dc-0516a7845a7f",
"0f83966e-0d22-427d-af74-35998d56a32c",
"0dfe435b-a3a8-4126-9bca-a45dd31331ff",
"0d2814f5-fca8-457f-bb6e-93554ac5c6ff",
"93a84a11-fc01-4afe-86f0-b5e53bfdcc65",
"47a6ba7a-fe39-4327-b78d-291c194ad35c",
"1a94fe9f-f261-41fc-831b-8f186286ae1d",
"fe204dc7-ca98-4fa2-9acb-8225499d0486",
"a609901f-ff23-49c1-9498-db46a6b5106d",
"ff251b59-5031-43a9-ac3c-d75810a3f3d8",
"70425e83-2e7a-4e9d-841a-c718a7af3c62",
"f5ab3624-1c08-4c41-adaf-228bb0efefa9",
"426b5c86-b071-4fc0-919b-c9a67d460bd1",
"d88d5541-63d6-4261-880b-2095a0455860",
"bc085f80-48c3-4507-8bdb-59e2e0cf05c0",
"212325f9-ca89-4f69-bd91-72ad85abc30a",
"29086a1f-2bb6-45da-97ed-e828229246ba",
"dda10796-3960-4bb0-894b-5600da4a6e8f",
"23a5848f-5e2b-49c5-84db-2d38b057c993",
"dcd813aa-fb6e-47d2-b794-14bf7fcf182e",
"dd8a623f-c5da-4aaf-9c9f-5fcf6c9c7d55",
"ffd03c19-370f-40c5-9bdd-989015020871",
"680c8004-dc47-43c2-8aec-cfcc2ac25160",
"db42a8fe-a143-4638-9462-22b560d2f97b",
"8c1b87f7-d093-428f-9b6a-c7999f2fb5fb",
"d759d1fc-dad4-4ada-88ab-d176bf2fa6e2",
"4a0cfe3f-ab33-4d8d-a59b-435d1e34e935",
"dceb58fb-8152-4b43-a494-d8ab0a9f7c3f",
"f262cbb3-54e3-49db-bf7f-6b619bf9a951",
"00026fe2-4de2-4378-ad4a-6337eb926e6d",
"4184c0a0-59ce-489a-aa44-6183974ffd3b",
"6bc9344b-9f28-4061-b8cf-eeccc2a9b50d",
"ef3e28ba-20da-431b-8e98-f672d7d5fa1e",
"99224fa9-df46-4bb8-abd3-69720fa9da4a",
"98f1acd1-1b2b-49c3-933a-f880f5f1f1d2",
"bf157247-d22c-4b1a-ba9f-7fd896a230ed",
"68ad95f1-8554-4015-9ead-1b951d8f6cd3",
"8a21b215-b3a2-423e-9667-23fea6cf8b7c",
        ]

        # 将多条记录推送到列表中
        try:
            for record in records:
                # 删除列表中所有与 record 相同的元素
                client.lrem('xmDigitalSignTask', 0, record)
            client.rpush('xmDigitalSignTask', *records)
            print("记录成功推送到 xmDigitalSignTask 列表中")
        except Exception as e:
            print(f"发生错误: {e}")

    def test_batch_create_sign_order(self):
        '''批量发起签署'''
        report_codes = [
  "CXLC-DH-2400431",
  "CXLC-DH-2400432",
  "CXLC-DH-2400433",
  "CXLC-DH-2400434",
  "CXLC-DH-2400435",
  "CXLC-DH-2400436",
  "CXLC-DH-2400437",
  "CXLC-DH-2400438",
        ]
        for report_code in report_codes:
            print(f"{report_code}正在发起签署...")
            result = yida_client.get_ids_by_search_field(
                report_form_uuid,
                admin_user_id,
                [
                    {
                      "type": "TEXT",
                      "operator": "eq",
                      "componentName": "TextField",
                      "key": "textField_lp93kxup",
                      "value": report_code
                    }
                ]
            )
            form_inst_id = result[0]
            res = requests.post("https://api.zjcxjc.cn/api/v1/yida-app/chengxiang/create_digital_sign_order",json={
                "form_inst_ids": [form_inst_id]
            })
            if res.status_code == 200:
                print("success")
    
    def copy_process_data(self):
        '''复制流程'''
        form_inst_ids = [
            "9d36fdcc-1e0d-4695-840d-d864a8b18f39",
        ]
        form_uuid = report_form_uuid
        for index,form_inst_id in enumerate(form_inst_ids):
            print(f"正在复制第{index}份>>>")
            result = yida_client.get_form_items_by_ids(form_uuid=form_uuid,
                                          form_inst_id=form_inst_id,
                                          userId=yida_client.admin_user_id)
            if not result:
                continue
            form_data = result[0].form_data
            creator = result[0].creator_user_id
            new_form_data = {}
            for key in form_data:
                if key.startswith("associationFormField"):
                    asso_key = key[:-3]
                    asso_val = json.loads(json.loads(form_data[key]))
                    new_form_data[asso_key] = asso_val
                elif key.endswith("_id"):
                    continue
                elif key.startswith("selectField"):
                    new_form_data[key] = form_data[key+"_id"]
                elif key.startswith("checkboxField"):
                    new_form_data[key] = form_data[key+"_id"]
                elif key.startswith("radioField"):
                    new_form_data[key] = form_data[key+"_id"]
                elif key.startswith("multiSelectField"):
                    new_form_data[key] = form_data[key+"_id"]
                elif key.startswith("employeeField"):
                    new_form_data[key] = form_data[key+"_id"]
                else:
                    new_form_data[key] = form_data[key]
            result = yida_client.create_process_instance(form_uuid=form_uuid,
                                        userId=creator,
                                        formDataJson=new_form_data,
                                        process_code="TPROC--U0A66091AZQGSDPIFBEQP8HN89KL39DYDE7QLO7")
            # 打开文件（如果文件不存在则会创建一个新文件）
            with open('/Users/xusijiao/Desktop/黄教授/aaa/1021.txt', 'a', encoding='utf-8') as file:
                # 写入要追加的字符串
                file.write(f'{result}\n')
            print(result)

    def alter_reportcode_batch(self):
        '''批量修复报告编号'''
        form_uuid = report_form_uuid
        form_inst_ids = [
            "02111248-b1d4-4d07-9fa5-2a21be5d0e50",
        ]
        for form_inst_id in form_inst_ids:
            result = yida_client.get_form_items_by_ids(form_uuid=form_uuid,
                                          form_inst_id=form_inst_id,
                                          userId=yida_client.admin_user_id)
            report_code = result[0].form_data.get("textField_lp93kxup")
            if(bool(re.search(r'\d{10}$', report_code))):
                new_report_code = report_code[:-5]
                print(new_report_code)
                result = yida_client.update_form_data_by_id(form_uuid=form_uuid,
                                          form_inst_id=form_inst_id,
                                          userId=yida_client.admin_user_id,
                                          update_field={
                                              "textField_lp93kxup":new_report_code,
                                          })
                print(result)
            else:
                print("格式不正确")

    def delete_report_batch(self):
        form_inst_ids = [
            "9d36fdcc-1e0d-4695-840d-d864a8b18f39",
        ]
        for form_inst_id in form_inst_ids:
            result = yida_client.delete_form_data(form_instance_id=form_inst_id,
                                                  userId=yida_client.admin_user_id)
            print(result)
      
    def update_area(self):
        '''修复地区'''
        form_uuid = report_form_uuid
        for form_inst_id in [
            "c1e69006-0f85-46a6-8fe6-07eac7529175",
            "1c4518e3-086b-4f4a-a0b8-c0682ba07176",
            "c871d3c0-8fc3-46b5-bfe9-827868e72e1c",
            "bf08fd67-e1b9-4e8a-86eb-9a51869a97e1",
            "8845a2d9-5310-4817-8f46-d306a0df8892",
        ]:
            result = yida_client.get_form_items_by_ids(form_uuid,form_inst_id,admin_user_id)
            if not result:
                continue
            form_data = result[0].form_data
            report_code = form_data.get("textField_lp93kxup")
            print(report_code)
            sn_1 = report_code[2]
            sn_2 = f"ZJ_{sn_1}_{report_code[5:7]}"
            print(sn_2)
            result = yida_client.update_form_data_by_id(form_uuid,admin_user_id,form_inst_id,{
                # "cascadeSelectField_lpgahbwq":area_id
                "cascadeSelectField_lpgahbwq":[
                    "ZJ",
                    sn_1,
                    sn_2
                ]
            })
            pass
        
    def update_bzy_by_upload_report(self):
      # 更新代写报告人为编制员
        # process_inst_ids = []
        # page = 1
        # page_size = 100
        # batch_size = 1000
        # batch_count = 7
        # while True:
        #     results,total = yida_client.get_process_ids_by_search_field(report_form_uuid,
        #                                                                 admin_user_id,
        #                                                                 "2024-05-01",
        #                                                                 "2024-10-01",
        #                                                                 page=page)
        #     process_inst_ids += results
        #     if len(process_inst_ids) >= batch_size:
        #         batch_data = process_inst_ids[:batch_size]
        #         process_inst_ids = process_inst_ids[batch_size:]  # 剩余的未保存数据

        #         # 创建一个新的工作簿
        #         wb = openpyxl.Workbook()
        #         ws = wb.active
        #         ws.title = f"Batch {batch_count}"

        #         # 将批量数据写入Excel
        #         for idx, process_inst_id in enumerate(batch_data, start=1):
        #             ws[f"A{idx}"] = process_inst_id

        #         # 保存到文件
        #         output_file = f"/Users/xusijiao/Downloads/aaap/process_{batch_count}.xlsx"
        #         wb.save(output_file)
        #         print(f"第{batch_count}批数据已保存到 {output_file}")

        #         # 更新批次号
        #         batch_count += 1
        #     if((page) * page_size >= total):
        #         break
        #     page += 1
        # print(f"获取到{total}条数据")
        # if process_inst_ids:
        #     wb = openpyxl.Workbook()
        #     ws = wb.active
        #     ws.title = f"Batch {batch_count}"

        #     # 将剩余的数据写入Excel
        #     for idx, process_inst_id in enumerate(process_inst_ids, start=1):
        #         ws[f"A{idx}"] = process_inst_id

        #     # 保存到文件
        #     output_file = f"/Users/xusijiao/Downloads/aaap/process_{batch_count}.xlsx"
        #     wb.save(output_file)
        #     print(f"第{batch_count}批数据已保存到 {output_file}")
        file_dir = f"/root/xm-detection-service/yida_app_service/chengxiang/resorce/tmp/"
        for batch_index in range(27,28):
            file_path = f"{file_dir}process_{batch_index}.xlsx"
            logging.info(f"正在处理第{batch_index}批...")
            wb = openpyxl.load_workbook(file_path)
            ws = wb.active
            process_inst_ids = []
            for row in ws.iter_rows(min_row=1, max_col=1, values_only=True):
                process_inst_ids.append(row[0])
            for index,process_inst_id in enumerate(process_inst_ids, start=1):
                # if index < 530:
                #     continue
                history_data = yida_client.get_approve_history(process_inst_id,admin_user_id)
                target_node = next((item for item in reversed(history_data) if (item.show_name == "待写报告" and item.action_exit == "agree")), None)
                if target_node:
                    bzy_id = target_node.operator_user_id
                    bzy_name = target_node.operator_name
                    form_data = yida_client.get_process_instance_by_id(admin_user_id,process_inst_id)
                    report_code = form_data.get("textField_lp93kxup")
                    logging.info(f"正在处理第{index+1}条数据,编号：{report_code}")
                    origin_bzy_id = form_data.get("selectField_lqwcqyd0_id")
                    if not bzy_id:
                        # raise Exception("数据异常，请检查数据")
                        continue
                    if bzy_id != origin_bzy_id:
                        res = yida_client.update_form_data_by_field(report_form_uuid,
                                                              admin_user_id,
                                                              [
                                                                  {
                                                                    "type": "TEXT",
                                                                    "operator": "eq",
                                                                    "componentName": "TextField",
                                                                    "key": "textField_lp93kxup",
                                                                    "value": report_code
                                                                  }
                                                              ],
                                                              {
                                                                  "selectField_lqwcqyd0":bzy_id,
                                                                  "employeeField_m1k1eva6":[bzy_id],
                                                                  "textField_lrd6lxm1":bzy_name
                                                              })
                        logging.info(res)
                    else:
                        logging.info("无需处理")
                    
            pass
        
    def update_report_items(self):
        form_inst_ids = [
            "4b926e54-3934-4df4-bac6-4a6aca4e53c7",
            "c1039bbf-f643-46df-9931-439ff2c5fd4f",
            "ea0c4390-1082-4449-b6a9-ecacffbfa3fa",
            "5abd92c0-7242-4945-9c65-a34909ccdb9c",
            "4596cb32-eda9-4567-81f6-4b51cc5a4ffd",
            "3d50fa86-2c97-45a5-8192-94f64543fd16",
            "f2988ab4-2fc5-41db-95e4-9cd7aaab3441",
        ]
        for index,form_inst_id in enumerate(form_inst_ids):
            if index < 81:
                continue
            print(f"正在处理第{index}条>>>",form_inst_id)
            res = yida_client.get_form_items_by_ids(
                report_form_uuid,
                form_inst_id,
                admin_user_id
            )
            if res:
                sample_name = res[0].form_data.get("associationFormField_m5fr6hbc_id")
                sample_name = json.loads(json.loads(sample_name))
                if not sample_name:
                    continue
                sample_name = sample_name[0].get("subTitle")
                update_res = yida_client.update_form_data_by_id(
                    report_form_uuid,
                    admin_user_id,
                    form_inst_id,
                    {
                        "textField_lr0cupsi":sample_name
                    }
                )
                print(update_res)
    
    def batch_gen_report(self):
        model_id = "PQ566991LOBRI9DJ9ZQQ14YDPZ5C2M161NW4M5T1"
        report_codes = [
            "CX02-010112500118",
            "CX02-010112500119",
            "CX02-010112500120",
            "CX02-010112500121",
            "CX02-010112500122",
            "CX02-010112500123",
            "CX02-010112500124",
            "CX02-010112500125",
            "CX02-010112500126",
            "CX02-010112500127",
            "CX02-010112500128",
            "CX02-010112500129",
            "CX02-010112500130",
            "CX02-010112500131",
            "CX02-010112500132",
        ]
        for index,report_code in enumerate(report_codes):
            results = yida_client.get_ids_by_search_field(
                report_form_uuid,
                admin_user_id,
                [
                    {
                        "type": "TEXT",
                        "operator": "eq",
                        "componentName": "TextField",
                        "key": "textField_lp93kxup",
                        "value": report_code
                    }
                ]
            )
            if results:
                form_inst_id = results[0]
                res = requests.post(
                    f"https://api.zjcxjc.cn/api/v1/yida-app/chengxiang_2025/gen_base/{model_id}",
                    json={
                        "form_inst_id": form_inst_id,
                        "hzfw":True
                    },
                    headers={
                        "Content-Type": "application/json",
                    }
                )
                if res.status_code == 200:
                    print("success")
        
    def update_finicial_bzy_info(self):
        bzy_id = "132058133925879495"
        person = yida_client.get_form_data_by_search_field(person_form_uuid,
                                                           admin_user_id,
                                                           [
                                                               {
                                                               "type": "TEXT",
                                                               "operator": "eq",
                                                               "componentName": "TextField",
                                                               "key": "textField_lp0zbal4",
                                                               "value": bzy_id
                                                           }
                                                           ])
        if not person:
            raise Exception("数据异常，请检查数据")
        else:
            bzy_name = person[0].form_data.get("textField_lp0tv654")
        results,total = yida_client.get_all_form_data_by_search_field(report_form_uuid,admin_user_id,[
            {
              "type": "TEXT",
              "operator": "eq",
              "componentName": "TextField",
              "key": "selectField_lqwcqyd0",
              "value": bzy_id
            },
        ])
        print(f"共计{total}条数据")
        for index,report_inst in enumerate(results):
            if index < 228:
                continue
            report_code = report_inst.form_data.get("textField_lp93kxup")
            sign_date = report_inst.form_data.get("dateField_lp92f309")
            print(f"正在处理第{index+1}条数据，编号：{report_code}")
            finicial_data = yida_client.get_form_data_by_search_field(finicial_form_uuid,
                                                      admin_user_id,
                                                      [
                                                          {
                                                              "type": "TEXT",
                                                              "operator": "eq",
                                                              "componentName": "TextField",
                                                              "key": "textField_ltmbnezf",
                                                              "value": report_code
                                                          }
                                                      ])
            if(len(finicial_data)>1):
                raise Exception("数据异常，请检查数据")
            elif len(finicial_data)==1:
                finicial_form_inst_id = finicial_data[0].form_instance_id
                res = yida_client.update_form_data_by_id(finicial_form_uuid,
                                                   admin_user_id,
                                                   finicial_form_inst_id,
                                                   {
                                                       "textField_lv0ntlyv":bzy_name,
                                                       "textField_m4j9xdl0":bzy_id,
                                                       "dateField_lv0uftfc":sign_date
                                                   })
                print(res)

        pass
    
    def archive_sign_data_to_xujf_com(self):
        import oss2
        auth = oss2.Auth("LTAI5t6uQ1q8XbgYHwVBG7k9", "Q0bBMa76xxGEE2pC6US6ifYDUc5tX7")
        cname = 'https://sign.zjxmyq.cn'
        xm_bucket = oss2.Bucket(auth, cname, 'xiaming-digitalsign',
                            is_cname=True, connect_timeout=30)
        objects = oss2.ObjectIteratorV2(xm_bucket)
        for index,obj in enumerate(objects):
            obj_key:str = obj.key
            if index < 45914:
                continue
            logging.info(f"正在迁移第{index + 1}份:{obj_key}")
            try:
                download_url = xm_bucket.sign_url('GET', obj_key, 3600)
                with requests.get(download_url) as response:
                    cover_content = response.content
                    ds_bucket.put_object(obj_key, cover_content)
                    logging.info("success")
            except Exception as e:
                with open('test_error.txt', 'a') as f:
                    logging.error(f"{obj_key}迁移失败")
                    f.write(f"{obj_key}\n")
    def test_gen_finicial_list(self):
        '''生成财务清单'''
        name = "吴兴区常溪单元2025"
        report_codes = [
"CX01-051452500004",
"CX01-051452500003",
"CX01-051452500005",
"CX01-050522500016",
"CX01-050522500015",
        ]
        all_reports = []
        for report_code in report_codes:
            report_res = yida_client.get_form_data_by_search_field(report_form_uuid,admin_user_id,[
                                                        {
                                                            "type": "TEXT",
                                                            "operator": "eq",
                                                            "componentName": "TextField",
                                                            "key": "textField_lp93kxup",
                                                            "value": report_code
                                                        }
                                                    ])
            if report_res:
                print(f"已找到报告：{report_code}")
                report_form_data = report_res[0].form_data
                report_info = {
                    "报告编号":report_code,
                    "工程名称": report_form_data.get("textField_lphpacz0"),
                    "委托单位":report_form_data.get("textField_lphpacz4"),
                    "样品名称":report_form_data.get("textField_lpb65tvd"),
                    "业务员":report_form_data.get("textField_lqetx3jq"),
                }
                finacial_res = yida_client.get_form_data_by_search_field(finicial_form_uuid,admin_user_id,[
                                                        {
                                                            "type": "TEXT",
                                                            "operator": "eq",
                                                            "componentName": "TextField",
                                                            "key": "textField_ltmbnezf",
                                                            "value": report_code
                                                        }
                                                    ])
                if finacial_res:
                    print(f"已找到财务表单：{report_code}")
                    finacial_form_data = finacial_res[0].form_data
                    report_info.update({
                        "总检测金额":finacial_form_data.get("numberField_lv0lyit8")
                    })
                else:
                    print(f"未找到财务表单：{report_code}")
                
                all_reports.append(report_info)
            else:
                print(f"未找到报告：{report_code}")
                all_reports.append({
                    "报告编号":report_code,
                })
        df = pd.DataFrame(all_reports)
        # 导出为Excel文件
        excel_file_path = f"/Users/xusijiao/Desktop/tmp_folder/{name}.xlsx"
        df.to_excel(excel_file_path, index=False, engine='openpyxl')

        print(f"报告清单已成功导出到: {excel_file_path}")
    def transfer_to_xu_com(self):
        '''文件迁移'''
        file_path = "yida_app_service/chengxiang/resorce/bak_lists/0101_0601.xlsx"
        wb = openpyxl.load_workbook(file_path)
        ws = wb.active
        process_inst_ids = []
        for row in ws.iter_rows(min_row=2, max_col=1, values_only=True):
            process_inst_ids.append(row[0])
        for form_inst_id in process_inst_ids:
            result = yida_client.get_form_items_by_ids(report_form_uuid,form_inst_id,admin_user_id)
            if result:
                start_backup_task_test(result[0],report_form_uuid)
            else:
                record_log(form_inst_id)
    
    def cache_finacial_data(self):
        '''缓存财务数据'''
        times_ranges = [
            ("2024-01-01","2024-02-01"),
            ("2024-02-01","2024-03-01"),
            ("2024-03-01","2024-04-01"),
            ("2024-04-01","2024-04-15"),
            ("2024-04-15","2024-05-01"),
            ("2024-05-01","2024-06-01"),
            ("2024-06-01","2024-07-01"),
            ("2024-07-01","2024-08-01"),
            ("2024-08-01","2024-09-01"),
            ("2024-09-01","2024-10-01"),
            ("2024-10-01","2024-11-01"),
            ("2024-11-01","2024-12-01"),
            ("2024-12-01","2025-01-01"),
        ]
        for batch_index,time_range in enumerate(times_ranges):
            print(f"正在缓存{time_range[0]}到{time_range[1]}的数据")
            results,total = yida_client.get_all_form_data_by_search_field(finicial_form_uuid,admin_user_id,[
                { "key": "currentNodeName", "value": ["结清"], "type": "ARRAY", "operator": "contains", "componentName": "TextField" },
            ],
                                                                      create_from_time_gmt=time_range[0],
                                                                      create_to_time_gmt=time_range[1])
            for index, result in enumerate(results):
                form_data = result.form_data
                value_obj = {
                    "form_data": form_data,
                    "form_instance_id":result.form_instance_id,
                    "process_status":"结清",

                }
                print(f"正在处理第{batch_index}组第{index}份报告：{form_data.get('textField_ltmbnezf')}")
                value = json.dumps(value_obj,skipkeys=True)
                key = f"chengxiang:form_data:{finicial_form_uuid}:{form_data.get('textField_ltmbnezf')}"
                cache.set(key,value,timeout=None)
        return "success"
    def download_fake_report_pdf(self):
        '''批量下载无章报告'''
        save_path = "/Users/xusijiao/Desktop/tmp_folder/report_out"
        report_codes = [
"CX02-550972500025",
"CX02-550972500026"
        ]
        for index,report_code in enumerate(report_codes):
            print(f"正在下载{report_code}...")
            result = requests.get(f"https://api.zjcxjc.cn/api/v1/yida-app/chengxiang/get_fake_sign_report?reportCode={report_code}")
            if result.status_code == 200:
                res_data = json.loads(result.text)
                down_url = res_data.get("data")
                if not down_url:
                    print("down_url is None")
                    continue
                down_res = requests.get(down_url)
                if down_res.status_code == 200:
                    file_content = down_res.content
                    with open(f"{save_path}/{report_code}.pdf", "wb") as file:
                        file.write(file_content)
                        print("success")
    def download_report_pdf(self):
        '''批量下载已签署的报告'''
        save_path = "/Users/xusijiao/Desktop/tmp_folder/report_out"
        report_codes = [
"CX02-212222500001",
"CX02-212232500001",
"CX02-212232500002",
"CX02-272212500002",
        ]
        for report_code in report_codes:
            print(f"正在下载{report_code}...")
            result = requests.get(f"https://api.zjcxjc.cn/api/v1/yida-app/chengxiang/get_whole_report?reportCode={report_code}")
            if result.status_code == 200:
                res_data = json.loads(result.text)
                down_url = res_data.get("data")
                down_res = requests.get(down_url)
                if down_res.status_code == 200:
                    file_content = down_res.content
                    with open(f"{save_path}/{report_code}.pdf", "wb") as file:
                        file.write(file_content)
                        print("success")
                        
    def batch_gen_report_code(self):
        file_path = "/Users/xusijiao/Downloads/项目信息-流程_20241231173509.xlsx"
        wb = openpyxl.load_workbook(file_path)
        ws = wb.active
        process_inst_ids = []
        for row in ws.iter_rows(min_row=2, max_col=1, values_only=True):
            process_inst_ids.append(row[0])
        for form_inst_id in process_inst_ids:
            res = requests.post("https://api.zjcxjc.cn/api/v1/yida-app/chengxiang/gen_serial_number_v2",json={
                "form_uuid": report_form_uuid,
                "sn_code": "CXAF-LP-24",
                "sn_code_field": "textField_lp93kxup",
                "zfill": 5,
                "form_inst_id":form_inst_id
            })
            if res.status_code == 200:
                print("success")

    def start_report_process(self):
        result = yida_client.create_process_instance(report_form_uuid,
                                            admin_user_id,
                                            {
                                                "cascadeSelectField_lpgahbwq":["ZJ","A","ZJ_A_XH"],
                                                "selectField_m5fq21f7":"测试",
                                                "dateField_lphnrozp":1736715165395
                                            },
                                            "TPROC--O8B66M71VNMR8BYRC3O7EDE47TBM2MZC1UB5M0")
        pass

    
def list_pdf_files(directory):
    paths = []
    # 遍历指定目录下的所有文件
    for filename in os.listdir(directory):
        # 检查文件是否为 PDF 文件
        if filename.endswith('.pdf'):
            print(filename)
            paths.append(filename)
    return paths

def start_backup_task_test(form_instance,form_uuid):
    
    logger.info(f"正在处理报告：{form_instance.form_data.get('textField_lp93kxup')}")
    try:
        report = Report.objects.get(report_code=form_instance.form_data.get('textField_lp93kxup'))
    except Report.DoesNotExist:
        logger.info(f"未找到报告：{form_instance.form_data.get('textField_lp93kxup')}")
        report = None
    except Report.MultipleObjectsReturned:
        logger.info(f"找到多个报告：{form_instance.form_data.get('textField_lp93kxup')}")
        reports = Report.objects.filter(report_code=form_instance.form_data.get('textField_lp93kxup')).order_by('-created_at')
        if reports.exists():
            report = reports.first()
            logger.info(f"找到多个报告，取最新报告：{report}")
        else:
            logger.info(f"未找到报告：{form_instance.form_data.get('textField_lp93kxup')}")
    except Exception as e:
        logger.info(f"处理报告时发生错误：{e}")
    if report:
        report_path = report.report_path
    else:
        report_path = f"tmp-out-pdf/{datetime.now().strftime('%Y%m%d')}/{uuid.uuid4()}"
    try:
        bak_attachment(form_instance,"attachmentField_lpb2cdkb",report_path,form_uuid)
        bak_attachment(form_instance,"attachmentField_lpb2cdka",report_path,form_uuid)
        bak_attachment(form_instance,"attachmentField_lpb2cdkd",report_path,form_uuid)
        bak_attachment(form_instance,"attachmentField_lpb2cdkf",report_path,form_uuid)
        bak_attachment(form_instance,"attachmentField_lqrz4ehj",report_path,form_uuid)
        if report:
            whole_path = f"{report_path}/whole.pdf"
            cover_docx_path = f"{report_path}/cover.docx"
            cover_path = f"{report_path}/cover.pdf"
            sign_path = f"{report_path}/sign.pdf"
            content_path = f"{report_path}/content.pdf"
            bak_report_attachement(whole_path)
            bak_report_attachement(cover_docx_path)
            bak_report_attachement(cover_path)
            bak_report_attachement(sign_path)
            bak_report_attachement(content_path)
    except Exception as e:
        logger.info(f"未知错误：{e}")
        record_log(form_instance.form_instance_id)
    yida_client.update_form_data_by_id(report_form_uuid,
                                        admin_user_id,
                                        form_instance.form_instance_id,
                                        {
                                            "selectField_m4wf9ayu":"是"
                                        })
    logger.info("迁移备份成功")
    time.sleep(3)

import oss2
auth = oss2.Auth("LTAI5t6uQ1q8XbgYHwVBG7k9", "Q0bBMa76xxGEE2pC6US6ifYDUc5tX7")
cname = 'https://sign.zjxmyq.cn'
xm_bucket = oss2.Bucket(auth, cname, 'xiaming-digitalsign',
                    is_cname=True, connect_timeout=30)
    
def bak_report_attachement(oss_key):
    if (not bucket.object_exists(oss_key)) and xm_bucket.object_exists(oss_key):
        logger.info("开始备份报告附件")
        download_url = xm_bucket.sign_url('GET', oss_key, 3600)
        response = requests.get(download_url)
        if response.status_code == 200:
            file_content = response.content
            bucket.put_object(oss_key, file_content)
    else:
        logger.info("报告附件已存在")

def bak_attachment(form_inst_data,field_name,report_path,form_uuid,retry=3):
    '''备份附件'''
    try:
        logger.info("备份地址"+report_path)
        if field_name not in form_inst_data.form_data:
            logger.info(f"{field_name}该字段无值")
            return
        attachments = json.loads(form_inst_data.form_data[field_name])
        new_attachments = []
        for index,attachment in enumerate(attachments):
            download_url:str = attachment.get("downloadUrl")
            if download_url.startswith("https://api.zjxmyq.cn"):
                oss_key = download_url.replace("https://api.zjxmyq.cn/api/v1/yida-app/common/download_file/","")
                exist = bucket.object_exists(oss_key)
                if exist:
                    xm_url = f"https://api.zjcxjc.cn/api/v1/yida-app/common/download_file/{oss_key}"
                    new_attachment = {
                            "downloadUrl": xm_url,
                            "name": attachment.get('name'),
                            "previewUrl": xm_url,
                            "url": xm_url,
                            "ext": attachment.get('name').split('.')[-1]
                        }
                    logger.info(f"{field_name}已备份已迁移，修改链接中")
                    new_attachments.append(new_attachment)
                    continue
                else:
                    logger.info(f"{field_name}已备份正在迁移")
            elif download_url.startswith("https://api.zjcxjc.cn"):
                logger.info(f"{field_name}已迁移，无需重复备份")
                new_attachments.append(attachment)
                continue
            else:
                full_download_url = yida_client.get_full_download_url(admin_user_id,download_url,True)
                download_url = full_download_url.body.result
            response = requests.get(download_url)
            if response.status_code == 200:
                file_content = response.content
                oss_path = f"{report_path}/{field_name}/{index}-{attachment.get('name')}"
                bucket.put_object(oss_path, file_content)
                xm_url = f"https://api.zjcxjc.cn/api/v1/yida-app/common/download_file/{oss_path}"
                new_attachment = {
                        "downloadUrl": xm_url,
                        "name": attachment.get('name'),
                        "previewUrl": xm_url,
                        "url": xm_url,
                        "ext": attachment.get('name').split('.')[-1]
                    }
                new_attachments.append(new_attachment)
        yida_client.update_form_data_by_id(form_uuid, admin_user_id, form_inst_data.form_instance_id, {
                    field_name: new_attachments
                })
        logger.info(f"{field_name}备份迁移成功")
    except Exception as e:
        print(f"宜搭接口调用错误：{e}")
        retry -= 1
        if retry > 0:
            bak_attachment(form_inst_data,field_name,report_path,form_uuid,retry)
        else:
            logger.info(f"{field_name}备份迁移失败")
            raise e


def record_log(form_inst_id):
    with open("yida_app_service/chengxiang/resorce/bak_lists/trans_err.txt", "a", encoding="utf-8") as file:
        file.write(f"{form_inst_id}\n")